package service

import (
	"shortlink/config"
	"shortlink/model"

	"github.com/astaxie/beego/orm"
)

func UpdateLink(id int64, url, longLink string) {
	link := &model.Link{
		Id: id,
	}

	config.LinkOrmer.Read(link)
	// link.Url = url
	link.Longlink = longLink

	config.LinkOrmer.Update(link)
}

func DelLink(id int64) {
	link := &model.Link{
		Id: id,
	}
	config.LinkOrmer.Delete(link)
}

func GetLinks() []*model.Link {
	ormer := config.LinkOrmer
	queryset := ormer.QueryTable(&model.Link{})
	var links []*model.Link
	queryset.All(&links)
	return links
}

func AddLink(url, slink, llink string) {
	ormer := config.LinkOrmer
	link := &model.Link{
		Url:       url,
		Shortlink: slink,
		Longlink:  llink,
	}
	ormer.Insert(link)
}

func GetLongLink(slink string) string {
	ormer := orm.NewOrm()
	link := &model.Link{
		Shortlink: slink,
	}
	if err := ormer.Read(link, "Shortlink"); err == nil {
		return link.Longlink
	}

	// fmt.Println("a", link)
	return ""

}

func GetLink(id int64) string {
	ormer := orm.NewOrm()
	link := &model.Link{
		Id: id,
	}
	if err := ormer.Read(link, "Id"); err == nil {
		return link.Longlink
	}

	// fmt.Println("a", link)
	return ""

}
